<template>
  <div class="chat-container">
    <div class="chat-messages" ref="messages">
      <div v-for="(message, index) in messages" :key="index" :class="{'user-message': message.isUser, 'bot-message': !message.isUser}">
        <span v-if="message.isUser" style="color: #000">{{ message.text }}</span>
        <MdPreview v-else v-model="message.text" :align="'left'" :defaultExpanded="true" style="background-color: #e0dfff;"/>
      </div>
    </div>
    <div class="input-container">
      <el-input class="input-msg" type="text" v-model="newMessage" :disabled="sending" @keyup.enter="sendMessage" ref="messageInput"
                placeholder="输入消息..."></el-input>
      <el-button type="primary" :disabled="sending" icon="Promotion" @click="sendMessage">发送</el-button>
    </div>
  </div>
</template>

<script>
import {MdPreview} from 'md-editor-v3';
import 'md-editor-v3/lib/preview.css';
import { SSE }from "sse.js/lib/sse.js"

export default {
  components: {
    MdPreview,
    SSE
  },
  data() {
    return {
      messages: [
        {text: '你好！我是你的本地AI大模型。', isUser: false}
      ],
      newMessage: '',
      sending: false,
      eventSource: null
    };
  },
  beforeDestroy() {
    this.stopSSE();
  },
  methods: {
    sendMessage() {
      if (this.newMessage.trim()) {
        this.messages.push({text: this.newMessage, isUser: true});

        // 禁用发送按钮
        this.sending = true;

        this.send(this.newMessage);


      }
    },
    focusInput() {
      // 设置焦点到输入框
      setTimeout(() => {
        this.$refs.messageInput.focus();
      }, 0);
    },
    activeButton() {
      // 清空输入框
      this.newMessage = '';
      // 重新启用发送按钮
      this.sending = false;
      // 重新将焦点设置到输入框
      this.focusInput();
    },
    scrollToBottom() {
      // 使用 setTimeout 确保 DOM 更新完毕后再滚动
      setTimeout(() => {
        this.$refs.messages.scrollTop = this.$refs.messages.scrollHeight;
      }, 0);
    },


    send(prompt) {
      // 创建一个新的机器人的消息
      this.messages.push({text: '', isUser: false});
      const url = 'http://127.0.0.1:8081/demo/stream';
      //this.startSSE(url + '?prompt=' + prompt);
      this.startSSE(url, prompt);
    },

    startSSE(url, prompt) {
      this.eventSource = new SSE(url,{
        method: 'POST',
        headers: {
          "Accept": "text/event-stream",
          "Content-Type":"application/json"
        },
        payload: JSON.stringify({"prompt": prompt}),
      });

      this.eventSource.onopen = (event) => {
        console.info('SSE opened')
      }
      this.eventSource.onmessage = (event) => {
        const data = JSON.parse(event.data);
        if (data.text === '[DONE]') {
          this.stopSSE();
          return;
        };
        const lastBotMessageIndex = this.messages.findLastIndex(message => !message.isUser);
        this.messages[lastBotMessageIndex].text += data.text;
      };

      this.eventSource.onerror = () => {
        this.stopSSE();
      };
    },
    stopSSE() {
      if (this.eventSource) {
        this.eventSource.close();
        console.info('SSE close')
        this.activeButton();
      }
    },

  },
  watch: {
    messages: {
      handler() {
        this.scrollToBottom();
      },
      deep: true
    }
  }
}
</script>


<style scoped>
body {
  margin: 0;
  font-family: 'Arial', sans-serif;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  overflow: hidden; /* 防止滚动条出现 */
  font-size: 16px; /* 增加全局字体大小 */
}

.chat-container {
  width: 100%;
  height: 100%;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-messages {
  /*flex: 1;*/
  overflow-y: auto;
  padding: 20px;
  height: 600px;
}

.chat-messages::-webkit-scrollbar {
  width: 8px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background-color: #cccccc;
  border-radius: 4px;
}

.chat-messages::-webkit-scrollbar-track {
  background-color: #f5f5f5;
}

.user-message,
.bot-message {
  padding: 10px 20px;
  /*border-radius: 0px;*/
  margin-bottom: 10px;
  max-width: 100%;
}

.user-message {
  text-align: right;
  background-color: #d3f9d3;
  margin-left: auto;
}

.bot-message {
  text-align: left;
  background-color: #e0dfff;
  margin-right: auto;
  padding: 0 0 0 0;
}

.input-container {
  display: flex;
  align-items: center;
  padding: 20px;
  background-color: #f5f5f5;
  border-top: 1px solid #e0e0e0;
}

.input-msg {
  border: 1px solid #e0e0e0;
  border-radius: 5px;
  margin-right: 10px;
}

</style>
